<!-- 评估报告表格 -->
<template>
  <div>
    <common-table
      :tableOptions="tableOptions"
      @onChange="handleConditionsChange"
      @onSortChange="onSortChange"
      @onFilterChange="onFilterChange"
      @rehandleSelectChange="onSelectChange"
    >
      <template #header>
        <t-space direction="vertical" style="width: 100%">
          <t-row justify="space-between">
            <t-button variant="outline" theme="primary" :disabled="!multiple" @click="handleMultipleDownload">
              批量下载
            </t-button>
            <t-input @change="search" clearable style="width: 200px">
              <search-icon slot="prefix-icon"></search-icon>
            </t-input>
          </t-row>
        </t-space>
      </template>
    </common-table>
    <t-dialog
      ref="dialog"
      width="700px"
      top="47px"
      :visible.sync="dialogVisible"
      header="报告预览"
      confirmBtn="下载"
      @confirm="handleDownloadPdf"
    >
      <survey-content
        ref="survey"
        class="survey-content"
        v-model="qsInformation.answer"
        :fileName="qsInformation.name"
        :questionnaireStatus="QUESTIONNAIRE_STATUS.PREVIEW"
        :questionObject="questionObject"
        :riskObject="qsInformation.qsRsTemplateList ?? {}"
      />
    </t-dialog>
  </div>
</template>

<script lang="jsx">
import CommonTable from '@/components/CommonTable/index.vue';
import SurveyContent from '@/components/SurveyContent/index.vue';
import { SearchIcon, DownloadIcon, BrowseIcon, TimeIcon, UserIcon } from 'tdesign-icons-vue';
import { mapState } from 'vuex';

import { requestQsList, requestQsListByPage } from '@/service/risk-assessment/management';
import { debounce } from '@/utils';
import { generateSurveyJsonAndQuestionObject } from '../utils/common';
import { QUESTIONNAIRE_STATUS } from '@/constants/risk-assessment-management';

export default {
  name: 'RAR-Table',
  components: { CommonTable, SearchIcon, SurveyContent },
  data() {
    return {
      QUESTIONNAIRE_STATUS,
      // dialog是否显示
      dialogVisible: false,
      qsInformation: {},
      questionObject: {},

      selectReports: [],
      downlodReports: [],
      multiple: false,
      oprationkW: {
        statusList: ['4'],
      }, // 搜索关键词、 筛选、排序
      tableOptions: {
        data: [],
        columns: [
          {
            colKey: 'row-select',
            type: 'multiple',
          },
          {
            // width: 120,
            colKey: 'name',
            title: '评估名称',
            // ellipsis: true,
            cell: (h, { row }) => <span style="color: #0052D9;">{row.name}</span>,
          },
          {
            colKey: 'answerName',
            title: '填写人',
            sortType: 'all',
            sorter: true,
            ellipsis: true,
            ellipsisTitle: false,
            // width: 150,
            filter: {
              type: 'multiple',
              resetValue: [],
              // 是否显示重置取消按钮
              showConfirmAndReset: true,
              list: [],
            },
            cell: (h, { row }) => (
              <div style="display: flex; align-items: center">
                <UserIcon />
                <span style="margin-left: 3px">{row.answerName}</span>
              </div>
            ),
          },
          {
            colKey: 'reviewName',
            title: '审核人',
            sortType: 'all',
            sorter: true,
            ellipsis: true,
            ellipsisTitle: false,
            // width: 150,
            // 输入框过滤配置
            filter: {
              type: 'multiple',
              resetValue: [],
              // 是否显示重置取消按钮
              showConfirmAndReset: true,
              list: [],
            },
            cell: (h, { row }) => (
              <div style="display: flex; align-items: center">
                <UserIcon />
                <span style="margin-left: 3px">{row.reviewName}</span>
              </div>
            ),
          },
          {
            colKey: 'complateTime',
            title: '完成时间',
            // width: 150,
            ellipsis: true,
            ellipsisTitle: false,
            sortType: 'all',
            sorter: true,
            cell: (h, { row }) => (
              <div style="display: flex; align-items: center">
                <TimeIcon />
                <span style="margin-left: 3px">{row.complateTime?.slice(0, 11)}</span>
              </div>
            ),
          },
          {
            colKey: 'action',
            title: '操作',
            width: 200,
            // 增、删、改、查 等操作
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            cell: (h, { row }) => (
              <div class="tdesign-table-demo__table-operations">
                <t-button variant="text" onClick={() => this.handlePreview(row)}>
                  <BrowseIcon />
                </t-button>
                <t-button variant="text" onClick={() => this.handleDownload(row)}>
                  <DownloadIcon />
                </t-button>
              </div>
            ),
          },
        ],
        pagination: {
          defaultCurrent: 1,
          defaultPageSize: 10,
          total: 0,
          showJumper: true,
        },
        config: {
          rowKey: 'id',
          hover: true,
        },
      },
    };
  },
  computed: {
    ...mapState('user', ['userInfo']),
  },
  mounted() {
    this.fetchData();
    this.$bus.$on('downloadingReport', () => {
      if (this.downlodReports.length === 0) return;
      const report = this.downlodReports.shift();
      this.handleDownload(report);
    });
  },
  methods: {
    fetchData() {
      const { defaultCurrent, defaultPageSize } = this.tableOptions.pagination;
      const pageObj = { pageNum: defaultCurrent, pageSize: defaultPageSize, ...this.oprationkW };
      requestQsListByPage(pageObj).then((res) => {
        if (!res || res.isError) return;
        const { resultQsVO, reviewNameSet, answerNameSet } = res;
        this.tableOptions.data = resultQsVO.list;
        this.tableOptions.pagination.total = resultQsVO.total;
        // 筛选数据
        this.tableOptions.columns[2].filter.list = [];
        this.tableOptions.columns[3].filter.list = [];
        for (let i = 0; i < answerNameSet?.length; i++) {
          if (!answerNameSet[i]?.rsUserId) {
            break;
          }
          this.tableOptions.columns[2].filter.list.push({
            label: answerNameSet[i]?.rsUserName,
            value: answerNameSet[i]?.rsUserId,
          });
        }
        for (let i = 0; i < reviewNameSet?.length; i++) {
          if (!reviewNameSet[i]?.rsUserId) {
            break;
          }
          this.tableOptions.columns[3].filter.list.push({
            label: reviewNameSet[i]?.rsUserName,
            value: reviewNameSet[i]?.rsUserId,
          });
        }
      });
    },
    async handleDownload({ id }) {
      await this.requestReportData(id);
      this.$nextTick(() => {
        this.handleDownloadPdf();
      });
    },
    handleMultipleDownload() {
      this.downlodReports = [...this.selectReports];
      const report = this.downlodReports.shift();
      this.handleDownload(report);
    },
    async handlePreview({ id }) {
      await this.requestReportData(id);
      this.dialogVisible = true;
    },
    handleDownloadPdf() {
      // 打印
      const pdfDom = this.$refs.survey.$refs.html2Pdf;
      pdfDom.generatePdf();
    },
    async requestReportData(id) {
      const res = await requestQsList(id);
      const { newObject, newJson } = generateSurveyJsonAndQuestionObject(res.question, res.name);
      this.qsInformation = res;
      this.questionObject = newObject;
      this.$refs.survey.init(newJson);
      this.$refs.survey.changeAnswerData(res.answer);
    },
    handleConditionsChange(info) {
      if (info?.pagination) {
        this.tableOptions.pagination.defaultCurrent = info?.pagination?.current;
        this.tableOptions.pagination.defaultPageSize = info?.pagination?.pageSize;
        this.fetchData();
      }
    },
    search: debounce(function fn(val) {
      this.oprationkW.inputContent = val;
      this.tableOptions.pagination.defaultCurrent = 1;
      // 没有搜索参数,接口要求也不传key
      if (!val) delete this.oprationkW.inputContent;
      this.fetchData();
    }, 1000),
    onSortChange(sort) {
      this.oprationkW.orderColum = sort?.sortBy;
      if (sort?.descending) {
        this.oprationkW.orderType = 'desc';
      } else {
        this.oprationkW.orderType = 'asc';
      }
      // 不排序的时候 不传参数
      if (!sort) {
        delete this.oprationkW.orderColum;
        delete this.oprationkW.orderType;
      }
      this.fetchData();
    },
    onFilterChange(filters) {
      this.tableOptions.pagination.defaultCurrent = 1;
      if (filters?.answerName && filters?.answerName.length > 0) {
        this.oprationkW.answerIdList = filters?.answerName;
      } else {
        delete this.oprationkW.answerIdList;
      }
      if (filters?.reviewName && filters?.reviewName.length > 0) {
        this.oprationkW.reviewIdList = filters?.reviewName;
      } else {
        delete this.oprationkW.reviewIdList;
      }
      this.fetchData();
    },
    onSelectChange(val, row) {
      this.selectReports = row;
      this.multiple = val.length > 0;
    },
  },
};
</script>
